<template>
  <view>
    <Loader :loading="loading">
      <view class="flex-col items-center group mt-20">
        <avatar v-model:avatar="inputs.avatar" :disabled="disableInputs"></avatar>
        <view class="flex-col section_4 mt-15">
          <view class="flex-row items-center group_2">
            <text class="font_2">用户名</text>
            <input :disabled="disableInputs" type="nickname" placeholder="点击输入" placeholder-style="placeholder-font"
              v-model="inputs.nickname" @blur="inputs.nickname = $event.target.value" class="grow ml-42" />
          </view>
          <view class="flex-row items-center group_3">
            <text class="font_2 text_6">出生日期</text>
            <picker :disabled="disableInputs" mode="date" :value="inputs.birthday" :start="startDate" :end="endDate"
              @change="inputs.birthday = $event.detail.value" class="grow ml-27">
              <view :class="{ 'placeholder-font': inputs.birthday == null }">{{
                inputs.birthday ?? "点击选择"
                }}</view>
            </picker>
          </view>
          <view class="flex-row items-center group_1">
            <text class="font_2 text_7">性别</text>
            <picker :disabled="disableInputs" mode="selector" :value="inputs.gender" :range="options.gender"
              @change="inputs.gender = Number($event.detail.value)" class="grow ml-59">
              <view :class="{ 'placeholder-font': inputs.gender == null }">{{
                inputs.gender == null ? "点击选择" : options.gender[inputs.gender]
                }}</view>
            </picker>
          </view>
          <view class="flex-row items-center group_4">
            <text class="font_2 text_9">婚姻状态</text>
            <picker :disabled="disableInputs" mode="selector" :value="inputs.marital_status"
              :range="options.marital_status" @change="inputs.marital_status = $event.detail.value" class="grow ml-25">
              <view :class="{ 'placeholder-font': inputs.marital_status == null }">
                {{
                  inputs.marital_status == null
                    ? "点击选择"
                    : options.marital_status[inputs.marital_status]
                }}</view>
            </picker>
          </view>
          <view class="flex-row items-center group_11">
            <text class="font_2">身高</text>
            <input :disabled="disableInputs" type="number" :value="inputs.height"
              @input="inputs.height = $event.target.value" class="grow ml-59" placeholder="点击输入" /><text>cm</text>
          </view>
          <view class="flex-row items-center group_5">
            <text class="font_2 text_12">体重</text>
            <input :disabled="disableInputs" :value="inputs.weight" @input="inputs.weight = $event.target.value"
              class="grow ml-58" placeholder="点击输入" /><text>kg</text>
          </view>
          <view class="flex-row items-center group_8">
            <text class="font_2 text_14">工作情况</text>
            <picker :disabled="disableInputs" mode="selector" :value="inputs.work_status" :range="options.work_status"
              @change="inputs.work_status = $event.detail.value" class="grow ml-26">
              <view :class="{ 'placeholder-font': inputs.work_status == null }">
                {{
                  inputs.work_status == null
                    ? "点击选择"
                    : options.work_status[inputs.work_status]
                }}</view>
            </picker>
          </view>
          <view class="flex-row items-center group_9">
            <text class="font_2 text_16">文化程度</text>
            <picker :disabled="disableInputs" mode="selector" :value="inputs.education_level"
              :range="options.education_level" @change="inputs.education_level = $event.detail.value" class="row ml-25">
              <view :class="{ 'placeholder-font': inputs.education_level == null }">
                {{
                  inputs.education_level == null
                    ? "点击选择"
                    : options.education_level[inputs.education_level]
                }}</view>
            </picker>
          </view>
          <view class="flex-row items-center group_6">
            <text class="font_2 text_18">居住地址</text>
            <picker :disabled="disableInputs" mode="region" class="grow group_12 ml-25" value="inputs.region"
              @change="inputs.region = $event.detail.value">
              <view :class="{ 'placeholder-font': inputs.region == null }">
                {{
                  inputs.region == null ? "点击选择" : inputs.region.join(",")
                }}</view>
            </picker>
          </view>
        </view>
        <button @click="onClickBottomButton" class="mt-15 submit-button"
          :class="{ 'submit-button-undone': isButtonDisable }" hover-class="submit-button-hover">
          {{ buttonText }}
        </button>
      </view>
    </Loader>
  </view>
</template>

<script>
import Avatar from "../../components/Avatar/Avatar.vue";
import Loader from "../../../components/Loader/Loader.vue";

export default {
  components: { Avatar, Loader },
  props: {
    showMode: {
      type: String,
      default: "first", // first, edit, view
      validator(value) {
        return ["first", "edit", "view"].includes(value);
      },
    },
  },
  data() {
    const currentDate = this.getDate();
    return {
      options: {
        gender: ["女", "男"],
        marital_status: ["未婚", "已婚", "分居", "离异", "丧偶"],
        work_status: ["在职", "已退休", "已离职"],
        education_level: [
          "文盲（未受过教育）",
          "小学",
          "初中",
          "高中/中专",
          "大专",
          "本科",
          "研究生及以上",
        ],
      },
      inputs: {
        avatar: null,
        nickname: null,
        birthday: null,
        gender: null,
        marital_status: null,
        height: null,
        weight: null,
        work_status: null,
        education_level: null,
        region: null,
      },
      curUserInfo: null,
      loading: true, // 页面加载状态
    };
  },

  watch: {},

  computed: {
    startDate() {
      return this.getDate("start");
    },
    endDate() {
      return this.getDate("end");
    },
    allDone() {
      return this.checkInputs();
    },
    buttonText() {
      if (this.showMode === "first" || this.showMode === "edit") {
        return this.allDone ? "提交" : "未完成";
      } else {
        return "编辑";
      }
    },
    isButtonDisable() {
      if (this.showMode === "first" || this.showMode === "edit") {
        return !this.allDone;
      } else {
        return false; // 在查看模式下不禁用按钮
      }
    },
    disableInputs() {
      return this.showMode === "view";
    },
  },

  async onShow() {
    // 每次显示页面时都获取最新的用户信息
    if (this.showMode === "edit" || this.showMode === "view") {
      try {
        this.loading = true;
        await this.loadUserInfo();
      } catch (error) {
        console.error('获取用户信息失败:', error);
        uni.showToast({
          title: "获取用户信息失败",
          icon: "error",
        });
      } finally {
        this.loading = false;
      }
    } else {
      this.loading = false;
    }
  },

  methods: {
    toNextPage() {
      if (this.showMode === "first") {
        this.$tabbar.switchTab({
          url: "/pages/resource/resource",
        });
      } else if (this.showMode === "view") {
        uni.navigateTo({
          url: "/sub_pages/pages/userinfo/userinfo?showMode=edit",
        });
      } else {
        uni.navigateBack();
      }
    },
    getDate(type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (type === "start") {
        year = year - 150;
      } else if (type === "end") {
        year = year + 2;
      }
      month = month > 9 ? month : "0" + month;
      day = day > 9 ? day : "0" + day;
      return `${year}-${month}-${day}`;
    },
    checkInputs() {
      for (const key in this.inputs) {
        if (this.inputs[key] === null) {
          return false;
        }
      }
      return true;
    },
    inputsToUserInfo(inputs) {
      return {
        nickname: this.inputs.nickname,
        avatar: this.inputs.avatar,
        birthday: this.inputs.birthday,
        gender: Number(this.inputs.gender),
        marital_status: this.inputs.marital_status,
        province: this.inputs.region[0],
        city: this.inputs.region[1],
        district: this.inputs.region[2],
        height: this.inputs.height,
        weight: this.inputs.weight,
        work_status: this.inputs.work_status,
        education_level: this.inputs.education_level,
      };
    },
    userInfoToInputs(userInfo) {
      return {
        avatar: userInfo.avatar,
        nickname: userInfo.nickname,
        birthday: userInfo.birthday,
        gender: userInfo.gender,
        marital_status: userInfo.marital_status,
        height: userInfo.height,
        weight: userInfo.weight,
        work_status: userInfo.work_status,
        education_level: userInfo.education_level,
        region: [userInfo.province, userInfo.city, userInfo.district],
      };
    },
    loadDefaultUserInfo() {
      this.inputs = {
        nickname: "微信用户",
      };
    },
    async loadUserInfo() {
      const userInfo = await this.$requests.getUserInfo({
        showLoading: true,
      });
      this.curUserInfo = userInfo;
      this.inputs = this.userInfoToInputs(userInfo);
    },
    onClickBottomButton() {
      if (this.showMode === "first" || this.showMode === "edit") {
        if (!this.allDone) {
          return;
        }
        this.submit();
      } else if (this.showMode === "view") {
        this.toNextPage();
      }
    },
    async submit() {
      console.log(this.inputs);
      if (!this.checkInputs()) {
        uni.showToast({
          title: "请填写完整信息",
          icon: "none",
        });
        return;
      }

      try {
        // 检查头像是否需要上传
        const needUploadAvatar = this.needUploadAvatar();

        if (needUploadAvatar) {
          await this.uploadAvatarAndSubmit();
        } else {
          await this.submitUserInfo();
        }
        
        // 只有成功后才进行setstatus和tonextpage
        this.$requests.setUserInfoStatus({ isDirty: true });
        this.toNextPage();
      } catch (error) {
        console.error('提交失败:', error);
        uni.showToast({
          title: "提交失败，请重试",
          icon: "error",
        });
      }
    },

    // 检查是否需要上传头像
    needUploadAvatar() {
      if (!this.inputs.avatar) {
        return false;
      }

      if (!this.curUserInfo) {
        return true;
      }

      // 比较当前头像与原始头像是否相同
      const currentAvatar = this.inputs.avatar;
      const originalAvatar = this.curUserInfo.avatar;

      return !currentAvatar.startsWith("cloud:") && currentAvatar !== originalAvatar;
    },

    // 上传头像并提交用户信息
    async uploadAvatarAndSubmit() {
      uni.showToast({
        title: "加载中",
        icon: "loading",
      });

      const filePath = this.inputs.avatar;
      const fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
      // 使用时间戳+文件名作为远程文件名
      const remoteFileName = `avatar/${Date.now()}_${fileName}`;

      return new Promise((resolve, reject) => {
        this.$requests.uploadFile({
          filePath: this.inputs.avatar,
          name: remoteFileName,
          success: async (res) => {
            try {
              this.inputs.avatar = res.fileID;
              await this.submitUserInfo();
              resolve();
            } catch (error) {
              reject(error);
            }
          },
          fail: (err) => {
            console.error("failed to upload", err);
            uni.hideToast();
            uni.showToast({
              title: "网络错误，请重新尝试",
              icon: "error",
            });
            reject(err);
          },
        });
      });
    },

    // 提交用户信息
    async submitUserInfo() {
      return new Promise((resolve, reject) => {
        this.$requests.request({
          url: "/user/modify/",
          method: "POST",
          data: this.inputsToUserInfo(this.inputs),
          success: (res) => {
            uni.hideToast();
            if (res.statusCode !== 200) {
              uni.showToast({
                title: "网络错误，请重新尝试",
                icon: "error",
              });
              reject(new Error(`HTTP ${res.statusCode}`));
              return;
            }
            resolve(res);
          },
          fail: (err) => {
            console.error("failed to submit", err);
            uni.hideToast();
            uni.showToast({
              title: "网络错误，请重新尝试",
              icon: "error",
            });
            reject(err);
          },
        });
      });
    },
  },
};
</script>

<style scoped lang="css">
.ml-27 {
  margin-left: 54rpx;
}

.ml-59 {
  margin-left: 118rpx;
}

.ml-25 {
  margin-left: 50rpx;
}

.ml-1 {
  margin-left: 2rpx;
}

.ml-3 {
  margin-left: 6rpx;
}

.mt-15 {
  margin-top: 30rpx;
}

.font_2 {
  font-size: 32rpx;
  color: #333333;
}

.group {
  padding: 0 55rpx;
}

.section_4 {
  padding: 9.5rpx 37rpx 10.5rpx 40rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
}

.group_2 {
  padding: 35.58rpx 0 11.98rpx;
}

.font_3 {
  font-size: 32rpx;
  line-height: 31.16rpx;
  color: #686868;
}

.group_3 {
  margin-top: 7.5rpx;
  padding: 27.3rpx 2.94rpx 20.48rpx;
  border-top: solid 2rpx #f5f5f5;
  border-bottom: solid 2rpx #f5f5f5;
}

.text_6 {
  line-height: 31.22rpx;
}

.group_1 {
  padding: 24.54rpx 0 21.64rpx;
  border-bottom: solid 2rpx #f5f5f5;
}

.text_7 {
  line-height: 30.82rpx;
}

.group_4 {
  padding: 25.36rpx 0 21.76rpx;
  border-bottom: solid 2rpx #f5f5f5;
}

.text_9 {
  line-height: 30.88rpx;
}

.group_11 {
  padding: 24.98rpx 0 21.86rpx;
  border-bottom: solid 2rpx #f5f5f5;
}

.group_5 {
  padding: 25.42rpx 0 17.86rpx;
  border-bottom: solid 2rpx #f5f5f5;
}

.text_12 {
  line-height: 30.68rpx;
}

.group_8 {
  padding: 25.26rpx 0 21.68rpx;
  border-bottom: solid 2rpx #f5f5f5;
}

.text_14 {
  line-height: 31.06rpx;
}

.group_9 {
  padding: 24.98rpx 0 21.64rpx;
  border-bottom: solid 2rpx #f5f5f5;
}

.text_16 {
  line-height: 31.32rpx;
}

.group_6 {
  margin-top: 10.5rpx;
  padding: 14.54rpx 0 33.08rpx;
}

.text_18 {
  line-height: 30.88rpx;
}

.group_12 {
  flex: 1 1 0;
}

.text_19 {
  line-height: 30.76rpx;
}

.text_20 {
  line-height: 30.54rpx;
}

.text_21 {
  line-height: 31.22rpx;
}

.text_22 {
  line-height: 30.76rpx;
}

.text_23 {
  line-height: 29.44rpx;
}

.submit-button {
  align-self: stretch;
  width: 640rpx;
  background-color: #f26a77;
  color: #ffffff;
  border-radius: 16rpx;
}

.submit-button-hover {
  background-color: #e56571;
}

.submit-button-undone {
  background-color: #979797 !important;
  color: #ffffff !important;
}

.placeholder-font {
  color: #686868;
}
</style>

<style>
page {
  background-color: #f5f5f5;
}
</style>